package com.sky.controller.admin;


import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags = "菜品相关接口")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @ApiOperation("新增菜品")
    public Result save(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品:{}", dishDTO);
        dishService.saveWithFlavor(dishDTO);
        //清理缓存
        String key = "dish_"+dishDTO.getCategoryId();
        cleanCache(key);
        return Result.success();
    }

    //这个业务和这个菜品分类这个表有关系，所以有点儿特殊
    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> page(DishPageQueryDTO dto) {
        log.info("菜品分页查询:{}", dto);
        PageResult page = dishService.pageQuery(dto);
        return Result.success(page);
    }


    @DeleteMapping
    @ApiOperation("用于删除员工")
    //菜品的删除与批量删除
    public Result delete(@RequestParam List<Long> ids){//将前端传来的这个String类型字符穿，按逗号分割装进列表
        log.info("菜品批量删除:{}", ids);
        dishService.deleteBatch(ids);
        //这里直接将所有下划线的dish全删除
       //先获取所有的key再删除
        cleanCache("dish_*");
        return Result.success();
    }

    //修改菜品
    //首先回显
    @GetMapping("/{id}")
    @ApiOperation("修改菜品回显")
    public Result<DishVO> getById(@PathVariable Long id){
        log.info("修改菜品回显:{}", id);
        DishVO dishVO = dishService.getByIdWithFlavor(id);
        return Result.success(dishVO);
    }
    //然后增加

    @PutMapping
    @ApiOperation("修改菜品")
    public Result update(@RequestBody DishDTO dishDTO){
        log.info("修改菜品:{}", dishDTO);
        dishService.updateWithFlavor(dishDTO);

        cleanCache("dish_*");//因为这个也可能影响多个数据极为复杂，我们直接全部删除

        return Result.success();
    }


    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> list(Long categoryId){
        log.info("根据分类id查询菜品");
        List<Dish> list = dishService.list(categoryId);
        return Result.success(list);
    }

    @PostMapping("/status/{status}")
    @ApiOperation("菜品起售和停止销售")
    public Result startOrStop(@PathVariable Integer status,Long id){
        log.info("<UNK>:{}", status);
        dishService.startOrStop(status,id);
        cleanCache("dish_*");
        return Result.success();
    }

    //统一抽取一个清理缓存的方法
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
